package com.briup.web.controller;

import com.briup.bean.User;
import com.briup.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpServletRequest;

@Controller
public class RegisterController {
    @Autowired
    private IUserService userService;

    @GetMapping(value = {"/toRegister","/register"})
    public String toRegister(HttpServletRequest request){

        return "register";
    }
    @PostMapping(value = "/register")
    public String userRegister(HttpServletRequest request, Model model) throws Exception {
        String loginName =  request.getParameter("loginName");
        String email =  request.getParameter("eMail");
        String phone =  request.getParameter("phone");
        //先根据loginName检查用户是否已经存在
        if(userService.findByLoginName(loginName) !=null){
            model.addAttribute("msg","用户账号已存在！");
            return "register";
        }
        else if(userService.findByEmail(email) !=null){
            model.addAttribute("msg","邮箱已注册！");
            return "register";
        }
        else if(userService.findByPhone(phone) !=null){
            model.addAttribute("msg","手机号已注册！");
            return "register";
        }
        User user = new User();
        user.setLoginName(loginName);
        user.setNickName(request.getParameter("nickName"));
        //将密码加密而不是使用密码存入数据库
        user.setPasswordMd5(DigestUtils.md5DigestAsHex(request.getParameter("passwordMd5").getBytes()));
        user.setAddress(request.getParameter("address"));
        user.setPhone(request.getParameter("phone"));
        user.setEMail(request.getParameter("eMail"));
        userService.register(user);
        return "redirect:/toLogin";
    }

}
